/**
 * 运费计算模块
 * 
 * 该模块是系统的核心功能模块，负责处理运费计算的所有相关业务逻辑。
 * 支持多种计费模式，包括首重续重模式和重量区间模式。
 * 集成了抛重计算、区域选择、策略匹配等复杂业务逻辑。
 * 
 * 主要功能：
 * - 运费计算（支持实重和抛重计算）
 * - 三级联动区域选择器（省市区级联选择）
 * - 策略自动匹配和手动选择
 * - 仓库和物流公司选择
 * - 计算结果展示和详情分析
 * - 区域数据缓存和智能加载
 * 
 * API调用统一管理：
 * - 计算运费：api.calculateFreight() -> POST /freight/calculate
 * - 策略计算：api.calculateFreightByStrategy() -> POST /freight/calculate
 * - 区域查询：通过全局区域数据获取
 * 
 * @author 运费系统团队
 * @version 2.0.0
 * @since 2025-08-29
 * @requires api.js - 统一API服务管理
 */

function useFreightCalculation() {
    const { ref, reactive } = Vue;
    // 响应式数据
    const calculating = ref(false);
    const freightResult = ref(null);

    const freightForm = reactive({
        weight: null,
        length: null,
        width: null,
        height: null,
        toAreaId: '',
        toProvinceName: '', // 新增：目标省份名称
        toCityName: '', // 新增：目标城市名称
        toDistrictName: '', // 新增：目标区县名称
        strategyId: '',
        warehouseCode: '',
        logisticsCompanyCode: ''
    });

    // 三级联动区域选择
    const areaTree = ref([]);
    const selectedProvince = ref(null);
    const selectedCity = ref(null);
    const selectedDistrict = ref(null);
    const showAreaSelector = ref(false);
    const isLoadingAreas = ref(false); // 添加加载状态
    const areaLoadRetryCount = ref(0); // 添加重试计数器
    const MAX_AREA_LOAD_RETRIES = 3; // 最大重试次数

    /**
     * 构建区域树结构
     */
    const buildFreightAreaTree = () => {
        // 从全局应用实例获取区域数据
        let allAreas = [];

        // 优先从Vue应用实例的areas属性获取
        if (window.vueAppInstance?.areas?.value) {
            allAreas = window.vueAppInstance.areas.value;
        } else if (window.vueAppInstance?.areas) {
            allAreas = window.vueAppInstance.areas;
        } else if (window.FreightApp?.getAllAreas) {
            allAreas = window.FreightApp.getAllAreas();
        }

        // 如果没有数据，直接返回，不使用模拟数据
        if (allAreas.length === 0) {
            console.warn('freight: 无法获取区域数据，区域选择器将显示为空');
            areaTree.value = [];
            return;
        }

        console.log('freight buildAreaTree开始，原始区域数据:', allAreas);

        // 数据预处理：确保有省级数据
        const processedAreas = preprocessAreaData(allAreas);
        console.log('freight buildAreaTree预处理后，区域数据:', processedAreas);

        const tree = [];
        // 使用更强的去重机制
        const uniqueProvinces = new Map();
        const uniqueCities = new Map();
        const uniqueDistricts = new Map();

        // 按层级分组数据，并进行去重
        processedAreas.forEach(area => {
            if (area.level === 1) {
                // 省级去重：使用provinceCode作为唯一标识
                const provinceKey = area.provinceCode;
                if (!uniqueProvinces.has(provinceKey)) {
                    const province = {
                        id: area.id,
                        code: area.provinceCode,
                        name: area.provinceName,
                        level: 1,
                        children: []
                    };
                    uniqueProvinces.set(provinceKey, province);
                    tree.push(province);
                    console.log('freight 添加省份:', area.provinceName, '(', area.provinceCode, ')');
                } else {
                    console.warn('freight 发现重复省份，已跳过:', area.provinceName, '(', area.provinceCode, ')');
                }
            } else if (area.level === 2) {
                // 市级去重：使用provinceCode+cityCode作为唯一标识
                const cityKey = `${area.provinceCode}|${area.cityCode}`;
                const provinceKey = area.provinceCode;

                if (!uniqueCities.has(cityKey)) {
                    const province = uniqueProvinces.get(provinceKey);
                    if (province) {
                        const city = {
                            id: area.id,
                            code: area.cityCode,
                            name: area.cityName,
                            provinceCode: area.provinceCode,
                            level: 2,
                            children: []
                        };
                        uniqueCities.set(cityKey, city);
                        province.children.push(city);
                        console.log('freight 添加城市:', area.cityName, '到省份:', area.provinceName, '(key:', cityKey, ')');
                    } else {
                        console.warn('freight: 找不到对应的省份数据:', area.provinceCode, area);
                    }
                } else {
                    console.warn('freight 发现重复城市，已跳过:', area.cityName, '(key:', cityKey, ')');
                }
            } else if (area.level === 3) {
                // 区县级去重：使用provinceCode+cityCode+districtCode作为唯一标识
                const districtKey = `${area.provinceCode}|${area.cityCode}|${area.districtCode}`;
                const cityKey = `${area.provinceCode}|${area.cityCode}`;

                if (!uniqueDistricts.has(districtKey)) {
                    const city = uniqueCities.get(cityKey);
                    if (city) {
                        const district = {
                            id: area.id,
                            code: area.districtCode,
                            name: area.districtName,
                            provinceCode: area.provinceCode,
                            cityCode: area.cityCode,
                            level: 3
                        };
                        uniqueDistricts.set(districtKey, district);
                        city.children.push(district);
                        console.log('freight 添加区县:', area.districtName, '到城市:', area.cityName);
                    } else {
                        console.warn('freight: 找不到对应的城市数据:', area.cityCode, '省份:', area.provinceCode, area);
                    }
                } else {
                    console.warn('freight 发现重复区县，已跳过:', area.districtName, '(key:', districtKey, ')');
                }
            }
        });

        areaTree.value = tree;
        console.log('freight buildAreaTree完成，区域数据:', processedAreas.length, '构建树节点:', tree.length);
        console.log('构建的区域树结构:', tree);
        console.log('去重统计 - 省份:', uniqueProvinces.size, '城市:', uniqueCities.size, '区县:', uniqueDistricts.size);
    };

    /**
     * 预处理区域数据，确保有省级数据
     */
    const preprocessAreaData = (areas) => {
        console.log('freight 开始数据预处理，原始数据:', areas);

        const result = [...areas];
        const existingProvinceCodes = new Set();
        const neededProvinces = new Set();

        // 收集现有的省级数据
        areas.forEach(area => {
            if (area.level === 1) {
                existingProvinceCodes.add(area.provinceCode);
            } else if (area.level >= 2) {
                neededProvinces.add(area.provinceCode);
            }
        });

        console.log('freight 现有省级数据:', Array.from(existingProvinceCodes));
        console.log('freight 需要省级数据:', Array.from(neededProvinces));

        // 为缺少的省级数据创建虚拟省份节点
        neededProvinces.forEach(provinceCode => {
            if (!existingProvinceCodes.has(provinceCode)) {
                console.log('freight 为省份编码创建虚拟省级数据:', provinceCode);

                // 从现有数据中找到第一个该省份的数据来获取省份名称
                const sampleArea = areas.find(area => area.provinceCode === provinceCode);
                if (sampleArea) {
                    // 使用时间戳确保ID唯一性
                    const virtualId = `virtual_freight_${provinceCode}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                    const virtualProvince = {
                        id: virtualId,
                        level: 1,
                        provinceCode: provinceCode,
                        provinceName: sampleArea.provinceName,
                        provinceShortName: sampleArea.provinceShortName || sampleArea.provinceName,
                        cityCode: null,
                        cityName: null,
                        districtCode: null,
                        districtName: null
                    };
                    result.push(virtualProvince);
                    console.log('freight 创建虚拟省级数据:', virtualProvince);
                }
            }
        });

        // 按层级排序，确保省级数据优先处理
        const sortedResult = result.sort((a, b) => a.level - b.level);
        console.log('freight 数据预处理完成，最终数据:', sortedResult);

        return sortedResult;
    };

    /**
     * 获取运费计算的Mock区域数据作为fallback
     * 注意：根据用户要求，不再使用模拟数据
     */
    const getFreightMockAreaData = () => {
        // 已废弃：不再使用模拟数据
        return [];
    };

    /**
     * 选择省份 - 用户可以只选择省份级别，不强制继续选择
     */
    const selectProvince = (province) => {
        console.log('选择省份:', province.name, '- 直接完成选择');

        // 清空所有选择状态
        selectedProvince.value = null;
        selectedCity.value = null;
        selectedDistrict.value = null;
        freightForm.toAreaId = '';

        // 直接设置目标区域ID和选中省份，立即关闭选择器
        freightForm.toAreaId = province.id;
        selectedProvince.value = province; // 保持对象引用用于显示
        showAreaSelector.value = false; // 选择省份后立即关闭选择器

        console.log('省份选择完成，选择器已关闭:', {
            toAreaId: freightForm.toAreaId,
            provinceName: province.name,
            selectorClosed: !showAreaSelector.value
        });
    };

    /**
     * 确认选择省份（双击或特定操作）
     */
    const confirmSelectProvince = (province) => {
        selectedProvince.value = province;
        selectedCity.value = null;
        selectedDistrict.value = null;
        freightForm.toAreaId = province.id;
        showAreaSelector.value = false;
    };

    /**
     * 选择城市 - 用户可以只选择城市级别，不强制继续选择区县
     */
    const selectCity = (city) => {
        console.log('选择城市:', city.name, '- 直接完成选择');

        selectedCity.value = city;
        selectedDistrict.value = null;

        // 设置目标区域并立即关闭选择器，不强制用户选择区县
        freightForm.toAreaId = city.id;
        showAreaSelector.value = false;

        console.log('城市选择完成，选择器已关闭:', {
            toAreaId: freightForm.toAreaId,
            cityName: city.name,
            selectorClosed: !showAreaSelector.value
        });
    };

    /**
     * 确认选择城市（双击或特定操作）
     */
    const confirmSelectCity = (city) => {
        selectedCity.value = city;
        selectedDistrict.value = null;
        freightForm.toAreaId = city.id;
        showAreaSelector.value = false;
    };

    /**
     * 选择区县 - 选择最细粒度的区域
     */
    const selectDistrict = (district) => {
        console.log('选择区县:', district.name, '- 完成最细粒度选择');

        selectedDistrict.value = district;
        freightForm.toAreaId = district.id;
        showAreaSelector.value = false;

        console.log('区县选择完成，选择器已关闭:', {
            toAreaId: freightForm.toAreaId,
            districtName: district.name,
            selectorClosed: !showAreaSelector.value
        });
    };

    /**
     * 获取选中区域的显示文本
     */
    const getSelectedAreaText = () => {
        if (selectedDistrict.value) {
            return `${selectedProvince.value.name} > ${selectedCity.value.name} > ${selectedDistrict.value.name}`;
        } else if (selectedCity.value) {
            return `${selectedProvince.value.name} > ${selectedCity.value.name}`;
        } else if (selectedProvince.value) {
            return selectedProvince.value.name;
        }
        return '请选择目标区域';
    };

    /**
     * 清空区域选择
     */
    const clearAreaSelection = () => {
        selectedProvince.value = null;
        selectedCity.value = null;
        selectedDistrict.value = null;
        freightForm.toAreaId = '';
    };

    /**
     * 切换区域选择器显示状态
     */
    const toggleAreaSelector = () => {
        showAreaSelector.value = !showAreaSelector.value;
        if (showAreaSelector.value) {
            // 每次打开都重新构建区域树，确保数据是最新的
            buildFreightAreaTree();

            // 如果还是没有数据且未超过重试次数，尝试重新加载区域数据
            setTimeout(() => {
                if (areaTree.value.length === 0 && !isLoadingAreas.value && areaLoadRetryCount.value < MAX_AREA_LOAD_RETRIES) {
                    console.log(`区域数据为空，尝试第${areaLoadRetryCount.value + 1}次重新加载...`);
                    isLoadingAreas.value = true;
                    areaLoadRetryCount.value++;

                    if (window.vueAppInstance?.loadAreas) {
                        window.vueAppInstance.loadAreas().then(() => {
                            buildFreightAreaTree();
                            isLoadingAreas.value = false;
                        }).catch((err) => {
                            console.error('加载区域数据失败:', err);
                            isLoadingAreas.value = false;
                        });
                    } else {
                        console.warn('无法获取loadAreas方法，请检查应用初始化');
                        isLoadingAreas.value = false;
                    }
                } else if (areaLoadRetryCount.value >= MAX_AREA_LOAD_RETRIES) {
                    console.warn('区域数据加载已达到最大重试次数，停止重试');
                }
            }, 100);

            // 添加全局点击事件监听器
            setTimeout(() => {
                document.addEventListener('click', handleOutsideClick);
            }, 10);
        } else {
            // 移除全局点击事件监听器
            document.removeEventListener('click', handleOutsideClick);
        }
    };

    /**
     * 处理外部点击事件
     */
    const handleOutsideClick = (event) => {
        const areaSelector = event.target.closest('.area-selector-container');
        if (!areaSelector && showAreaSelector.value) {
            showAreaSelector.value = false;
            document.removeEventListener('click', handleOutsideClick);
        }
    };

    // 鼠标离开延迟定时器
    let mouseLeaveTimer = null;

    /**
     * 处理区域选择器鼠标离开事件
     */
    const handleAreaSelectorMouseLeave = () => {
        console.log('鼠标离开区域选择器');
        // 设置延迟关闭，给用户一个缓冲时间
        mouseLeaveTimer = setTimeout(() => {
            if (showAreaSelector.value) {
                showAreaSelector.value = false;
                document.removeEventListener('click', handleOutsideClick);
                console.log('鼠标离开后自动关闭选择器');
            }
        }, 300); // 300ms延迟，给用户缓冲时间
    };

    /**
     * 处理区域选择器鼠标进入事件
     */
    const handleAreaSelectorMouseEnter = () => {
        console.log('鼠标进入区域选择器');
        // 取消延迟关闭
        if (mouseLeaveTimer) {
            clearTimeout(mouseLeaveTimer);
            mouseLeaveTimer = null;
            console.log('取消延迟关闭');
        }
    };

    /**
     * 计算运费
     */
    const calculateFreight = async () => {
        if (!freightForm.weight || !freightForm.toAreaId) {
            window.showMessage('请填写必要信息', true);
            return;
        }

        calculating.value = true;
        freightResult.value = null;

        try {
            const result = await window.FreightApp.api.calculateFreight(freightForm);
            if (result.code === 0) {
                freightResult.value = {
                    ...result.data,
                    detailedFormula: generateDetailedFormula(result.data)
                };
                window.showMessage('运费计算成功');
            } else {
                window.showMessage(result.msg || '计算失败', true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        } finally {
            calculating.value = false;
        }
    };

    /**
     * 生成详细的计算公式
     */
    const generateDetailedFormula = (data) => {
        if (!data) return '计算公式不可用';

        const {
            actualWeight,
            volumetricWeight,
            chargeableWeight,
            firstWeightKg,
            firstWeightFee,
            additionalWeight,
            additionalWeightFee,
            freight,
            usedWeightSegment,
            volumetricWeightRatio
        } = data;

        let formula = '';

        // 1. 体积重计算（如果有尺寸信息）
        if (freightForm.length && freightForm.width && freightForm.height) {
            const volume = freightForm.length * freightForm.width * freightForm.height; // 立方厘米
            const volumeM3 = (volume / 1000000).toFixed(6); // 立方米
            // 从全局配置获取转换系数，如果配置不存在则使用默认值
            const weightRatio = volumetricWeightRatio || 
                (window.FREIGHT_CONFIG ? window.FREIGHT_CONFIG.weightConversionFactor * window.FREIGHT_CONFIG.volumeConversionFactor / 1000000 : 0);

            formula += `📦 体积重计算：\n`;
            formula += `   长×宽×高 = ${freightForm.length}cm × ${freightForm.width}cm × ${freightForm.height}cm = ${volume.toLocaleString()}cm³\n`;
            formula += `   体积 = ${volume.toLocaleString()}cm³ ÷ 1,000,000 = ${volumeM3}m³\n`;
            formula += `   抛重比 = ${weightRatio.toLocaleString()} (每立方米按${weightRatio}kg计算)\n`;
            formula += `   体积重 = ${volume.toLocaleString()}cm³ ÷ ${weightRatio.toLocaleString()} = ${volumetricWeight}kg\n\n`;
        }

        // 2. 计费重量计算
        formula += `⚖️ 计费重量确定：\n`;
        if (volumetricWeight && volumetricWeight > actualWeight) {
            formula += `   实际重量 = ${actualWeight}kg\n`;
            formula += `   体积重量 = ${volumetricWeight}kg\n`;
            formula += `   计费重量 = max(${actualWeight}kg, ${volumetricWeight}kg) = ${chargeableWeight}kg（取较大值）\n\n`;
        } else {
            formula += `   实际重量 = ${actualWeight}kg\n`;
            if (volumetricWeight && volumetricWeight > 0) {
                formula += `   体积重量 = ${volumetricWeight}kg\n`;
                formula += `   计费重量 = max(${actualWeight}kg, ${volumetricWeight}kg) = ${chargeableWeight}kg（取较大值）\n\n`;
            } else {
                formula += `   计费重量 = ${chargeableWeight}kg（按实际重量计费）\n\n`;
            }
        }

        // 3. 运费计算
        formula += `💰 运费计算：\n`;
        if (usedWeightSegment) {
            // 使用了重量区间规则
            formula += `   计费模式：重量区间规则\n`;
            formula += `   ${chargeableWeight}kg 直接对应区间费率 = ${freight}元\n`;
        } else {
            // 使用首重续重计算
            formula += `   计费模式：首重续重\n`;
            formula += `   首重：${firstWeightKg}kg × ${firstWeightFee}元/kg = ${firstWeightFee}元\n`;

            if (additionalWeight > 0) {
                const additionalFee = (additionalWeight * additionalWeightFee).toFixed(2);
                formula += `   续重：${additionalWeight}kg × ${additionalWeightFee}元/kg = ${additionalFee}元\n`;
                formula += `   总计：${firstWeightFee}元 + ${additionalFee}元 = ${freight}元\n`;
            } else {
                formula += `   总计：${freight}元（未超过首重）\n`;
            }
        }

        return formula;
    };

    /**
     * 重置运费计算表单
     */
    const resetFreightForm = () => {
        Object.assign(freightForm, {
            weight: null,
            length: null,
            width: null,
            height: null,
            toAreaId: '',
            toProvinceName: '', // 重置地址层级字段
            toCityName: '',
            toDistrictName: '',
            strategyId: '',
            warehouseCode: '',
            logisticsCompanyCode: ''
        });
        freightResult.value = null;
        clearAreaSelection();
        
        // 重置策略搜索（如果在全局环境中存在）
        if (window.vueAppInstance?.strategySearchKeyword) {
            window.vueAppInstance.strategySearchKeyword.value = '';
        }
        if (window.vueAppInstance?.showStrategyDropdown) {
            window.vueAppInstance.showStrategyDropdown.value = false;
        }
        if (window.vueAppInstance?.filteredStrategies) {
            window.vueAppInstance.filteredStrategies.value = [];
        }
    };

    /**
     * 验证运费表单数据
     */
    const validateFreightForm = () => {
        const errors = [];

        if (!freightForm.weight || freightForm.weight < 0) {
            errors.push('货物重量不能为负数');
        }

        if (!freightForm.toAreaId) {
            errors.push('请选择目标区域');
        }

        if (freightForm.length && freightForm.length < 0) {
            errors.push('长度不能为负数');
        }

        if (freightForm.width && freightForm.width < 0) {
            errors.push('宽度不能为负数');
        }

        if (freightForm.height && freightForm.height < 0) {
            errors.push('高度不能为负数');
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    /**
     * 计算体积重量
     */
    const calculateVolumetricWeight = () => {
        if (!freightForm.length || !freightForm.width || !freightForm.height) {
            return null;
        }

        // 标准体积重量计算: 长 * 宽 * 高 / 5000
        const volumetricWeight = (freightForm.length * freightForm.width * freightForm.height) / 5000;
        return Math.round(volumetricWeight * 100) / 100; // 四舍五入到小数点后两位
    };

    /**
     * 获取计费重量（实际重量和体积重量中的较大值）
     */
    const getChargeableWeight = () => {
        const actualWeight = freightForm.weight || 0;
        const volumetricWeight = calculateVolumetricWeight();

        if (volumetricWeight === null) {
            return actualWeight;
        }

        return Math.max(actualWeight, volumetricWeight);
    };

    /**
     * 格式化运费结果用于显示
     */
    const formatFreightResult = (result) => {
        if (!result) return null;

        return {
            freight: result.freight ? `¥${result.freight.toFixed(2)}` : 'N/A',
            chargeableWeight: result.chargeableWeight ? `${result.chargeableWeight}kg` : 'N/A',
            strategyName: result.strategyName || '未知策略',
            breakdown: result.breakdown || []
        };
    };

    return {
        // State
        calculating,
        freightResult,
        freightForm,
        areaTree,
        selectedProvince,
        selectedCity,
        selectedDistrict,
        showAreaSelector,
        isLoadingAreas,
        areaLoadRetryCount,

        // Methods
        calculateFreight,
        resetFreightForm,
        validateFreightForm,
        calculateVolumetricWeight,
        getChargeableWeight,
        formatFreightResult,

        // 区域选择方法
        buildFreightAreaTree,
        selectProvince,
        selectCity,
        selectDistrict,
        confirmSelectProvince,
        confirmSelectCity,
        getSelectedAreaText,
        clearAreaSelection,
        toggleAreaSelector,
        handleOutsideClick,
        handleAreaSelectorMouseLeave,
        handleAreaSelectorMouseEnter,
        generateDetailedFormula
    };
}
